<?php
/**
 * Created by PhpStorm.
 * User: lhl
 * Date: 2020/10/19
 * Time: 17:24
 * Features: 后台角色权限中间关系
 */

namespace app\adminapiv3\model;


use app\common\service\ArrayHelper;
use think\Db;
use think\Exception;

class ServerGroupAuthMappingModel extends BaseModel
{
    /**
     * 根据角色id字符串,查询其权限数据
     * @param string $roleIdStr    角色id字符串
     * @param bool  $isRouteSystem 路由地址是否拼接系统前缀
     *
     * @return array
     * [
     *      'auths' => 权限数据
     *      'route' => 去重后的权限路由数据
     * ]
     */
    public function getAuthByRoleStr($roleIdStr){
        if(!$roleIdStr){
            throw new Exception('参数错误');
        }

        $auths = $this->alias('ra')     //角色-权限中间表
            ->join('server_permission a','ra.auth_id=a.id','left') //关联权限表
            ->where([
                ['ra.group_id','in',$roleIdStr],
            ])->order(['a.sorts' => 'asc','a.path' => 'asc'])
            ->field('a.id as auth_id,a.name,a.is_menu,a.icon,a.pid,a.path,a.level,a.root,a.route,a.redirect_url,a.menu_name,a.sorts')
            ->select()->toArray();

        if(!$auths){
            return [
                'auths' => null,
                'route' => null
            ];
        }

        //将权限数据根据权限id去重
        $auths = ArrayHelper::arrayUnique($auths,'auth_id');
        $route = array_unique(array_filter(array_column($auths,'route')));
        return [
            'auths' => $auths,
            'route' => $route
        ];
    }

    /**
     * 查询所有的权限及对应路由
    */
    public function getAllAuth(){
        $auths = Db::name('server_permission')->alias('a')
            ->order(['a.sorts' => 'asc','a.path' => 'asc'])
            ->field('a.id as auth_id,a.name,a.is_menu,a.icon,a.pid,a.path,a.level,a.root,a.route,a.redirect_url,a.menu_name,a.sorts')
            ->select();

        if(!$auths){
            return [
                'auths' => null,
                'route' => null
            ];
        }

        //将权限数据根据权限id去重
        $auths = ArrayHelper::arrayUnique($auths,'auth_id');
        $route = array_unique(array_filter(array_column($auths,'route')));
        return [
            'auths' => $auths,
            'route' => $route
        ];
    }

}